package com.situ.ymall.intercepter;

import com.situ.ymall.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
拦截器的写法

1 - 创建一个类，实现HandlerIntercepter
2-  加上@Component
3-  实现相应的方法
4-  创建一个SpringMVC的配置类，实现WebMVCConfigurer
5-  实现addIntercepters的方法
 */
@Component
public class UserIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断用户是否登陆
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null){
            return true;
        }else {
            //跳转到登录页面
            response.sendRedirect("/user/login");
            return false;
        }
    }
}
